import es
import playerlib
import weaponlib

from wcs.libs.items import items
from wcs.libs.players import players

itemName = "Ankh of Reincarnation"

item = items.addItem(itemName)
item.setGroup("special")
item.setCost(2000)
item.setDescription("Save your weapon information")
item.appendToUser = False
item.aliveToUse = True
        
def player_spawn(event_var):
    """
    Executed when a player spawns on the map. Ensure that we test to see if they
    have the item active, if so, give them the weapons back.
    """
    userid = event_var["userid"]
    if userid not in players:
        return
    if "ankh" not in players[userid]:
        return
    ankh = players[userid]["ankh"]
    if ankh["active"]:
        primary = ankh["primary"]
        secondary = ankh["secondary"]
        message = "#greeen%s #default- #lightgreenGiving you weapons (%s, %s)"
        es.tell(userid, "#multi", message % (itemName, primary, secondary))
        es.fire(userid, "player_weaponstrip", "kill")
        es.give(userid, "player_weaponstrip")
        es.fire(userid, "player_weaponstrip", "strip")
        es.give(userid, "weapon_knife")
        if primary is not None:
            es.give(userid, primary.name)
        if secondary is not None:
            es.give(userid, secondary.name)
        del players[userid]["ankh"]
        
def wcs_item_bought(event_var):
    """
    Executed when an item is brought. Check if the item bought was this item, if
    so, retrieve the current primary and secondary weapon and ensure that their
    values are stored.
    """
    if event_var['item'] == itemName:
        userid = event_var["userid"]
        message = "#green%s #default- #lightgreenWeapon info saved!"
        es.tell(userid, '#multi', message % itemName)
        player = playerlib.getPlayer(userid)
        players[userid]["ankh"] = {}
        players[userid]["ankh"]["active"] = False
        primary = player.primary
        secondary = player.secondary
        players[userid]["ankh"]["primary"] = weaponlib.getWeapon(primary)
        players[userid]["ankh"]["secondary"] = weaponlib.getWeapon(secondary)
        
def player_death(event_var):
    """
    Executed when the player dies. If the player has this item, ensure that the
    active state is assigned to True so that next respawn will ensure that they
    receive their weapons again.
    """
    userid = event_var["userid"]
    player = players[userid]
    if "ankh" in player and player["ankh"]["active"] is False:
        player["ankh"]["active"] = True